package com.base.moduleAI.service.impl;

import com.base.core.common.utils.MarkdownToHtmlUtils;
import com.base.moduleAI.entity.dto.AIPublishArticleDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Data
@Slf4j
@Component
public class CsdnArticlePublisher {

    private static final String CSDN_API_URL = "https://bizapi.csdn.net/blog-console-api/v1/postedit/saveArticle";
    private static final String COOKIE ="uuid_tt_dd=10_20146973410-1749692780117-189042; fid=20_36156370099-1749692785080-194188; UN=m0_75238321; p_uid=U010000; csdn_newcert_m0_75238321=1; c_ab_test=1; c_adb=1; creative_btn_mp=3; c_first_ref=cn.bing.com; c_first_page=https%3A//blog.csdn.net/stpeace/article/details/79845880; c_segment=2; Hm_lvt_6bcd52f51e9b3dce32bec4a3997715ac=1756348243,1756871459,1756949932,1757034317; HMACCOUNT=AC62E4F1ED476F44; dc_sid=67f84932a44bfa82a2d55178c5a82fc6; _clck=11t16ew%5E2%5Efz2%5E0%5E1989; dc_session_id=10_1757036864493.595762; c_dsid=11_1757036880302.203620; c_utm_term=java%20%E5%8F%91%E9%80%81https%20post%E8%AF%B7%E6%B1%82; fe_request_id=1757036881107_1083_0699141; c_utm_source=cknow_so_nontop_query; utm_source=cknow_so_nontop_query; referrer_search=1757036890188; c_dl_prid=-; c_dl_rid=1757036920556_335038; c_dl_fref=https://so.csdn.net/so/search; c_dl_fpage=/download/dulinanaaa/9699967; c_dl_um=distribute.pc_search_result.none-task-blog-2%7Eall%7Etop_click%7Edefault-2-135471612-null-null.142%5Ev102%5Epc_search_result_base3; relevant_index=1; c_utm_relevant_index=8; SESSION=60fdc8c7-f5fe-46c7-b95b-eb166f143b51; c_utm_medium=distribute.pc_search_result.none-task-blog-2%7Eall%7Etop_click%7Edefault-2-135471612-null-null.142%5Ev102%5Epc_search_result_base3; hide_login=1; loginbox_strategy=%7B%22taskId%22%3A317%2C%22abCheckTime%22%3A1757037606880%2C%22version%22%3A%22ExpA%22%2C%22nickName%22%3A%22Agoni9511%22%2C%22blog-threeH-dialog-expa%22%3A1757037606881%7D; UserName=m0_75238321; UserInfo=93ba88de3db746df97f6ce25114e7ac9; UserToken=93ba88de3db746df97f6ce25114e7ac9; UserNick=Agoni9511; AU=5B9; BT=1757037626484; _clsk=3ht8xm%5E1757037642747%5E11%5E0%5Ey.clarity.ms%2Fcollect; c_pref=https%3A//blog.csdn.net/m0_75238321%3Ftype%3Dblog; c_ref=https%3A//mp.csdn.net/; c_page_id=default; log_Id_pv=16; Hm_lpvt_6bcd52f51e9b3dce32bec4a3997715ac=1757037657; log_Id_view=618; log_Id_click=18; dc_tos=t23exw";
    private static final String X_CA_KEY = "203803574";
    private final ObjectMapper objectMapper;

    public CsdnArticlePublisher(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
    /**
     * 创建并配置HTTP POST请求
     */
    public  HttpPost createHttpPost(String requestBody) throws Exception {
        HttpPost httpPost = new HttpPost(CSDN_API_URL);
        // 设置请求头
        httpPost.setHeader("accept", "application/json, text/plain, */*");
        httpPost.setHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        httpPost.setHeader("content-type", "application/json;");
        httpPost.setHeader("cookie", COOKIE);
        httpPost.setHeader("origin", "https://mp.csdn.net");
        httpPost.setHeader("priority", "u=1, i");
        httpPost.setHeader("referer", "https://mp.csdn.net/");
        httpPost.setHeader("sec-ch-ua", "\"Not;A=Brand\";v=\"99\", \"Microsoft Edge\";v=\"139\", \"Chromium\";v=\"139\"");
        httpPost.setHeader("sec-ch-ua-mobile", "?0");
        httpPost.setHeader("sec-ch-ua-platform", "\"Windows\"");
        httpPost.setHeader("sec-fetch-dest", "empty");
        httpPost.setHeader("sec-fetch-mode", "cors");
        httpPost.setHeader("sec-fetch-site", "same-site");
        httpPost.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0");
        httpPost.setHeader("x-ca-key", X_CA_KEY);
        httpPost.setHeader("x-ca-nonce", "d7044c49-40f8-43d4-a6ee-7a63c77ff67c");
        httpPost.setHeader("x-ca-signature", "5E2dUYyTgqGADhoi9gm1RgqEVOeL4cUAfe7YYW4KJi4=");
        httpPost.setHeader("x-ca-signature-headers", "x-ca-key,x-ca-nonce");
        httpPost.setEntity(new StringEntity(requestBody, "UTF-8"));
        return httpPost;
    }
    /**
     * 执行HTTP请求
     */
    /**
     * 执行HTTP请求并返回原始响应体
     * @param httpPost 配置好的HTTP POST请求
     * @return 响应体字符串
     * @throws IOException 当请求执行或响应处理出错时抛出
     */
    public  String executeRequest(HttpPost httpPost) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {

            HttpEntity entity = response.getEntity();
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            // 检查HTTP状态码
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new IOException("CSDN API返回错误状态码: "
                        + response.getStatusLine().getStatusCode()
                        + ", 响应体: " + responseBody);
            }

            return responseBody;
        }
    }  /**
     * 构建CSDN发布请求体
     */
    public String buildPublishRequest(AIPublishArticleDTO articleDTO, String aiGeneratedContent) throws Exception {
        // 1. 内容转换
        String htmlContent = MarkdownToHtmlUtils.markdownToHtml(aiGeneratedContent);
        log.debug("Markdown转换HTML结果: {}", htmlContent);
        // 2. 构建基础payload
        Map<String, Object> payload = buildBasePayload(
                articleDTO.getKeywords().get(0),
                htmlContent,
                getDefaultTags()
        );

        // 3. 转换为JSON
        return objectMapper.writeValueAsString(payload);
    }

    /**
     * 构建基础payload结构
     */
    private Map<String, Object> buildBasePayload(String title, String content, List<String> tags) {
        Map<String, Object> payload = new LinkedHashMap<>();

        // 文章基础信息
        payload.put("article_id", "");
        payload.put("title", title);
        payload.put("description", "");
        payload.put("content", content);
        payload.put("tags", String.join(",", tags));

        // 发布配置
        payload.put("categories", "");
        payload.put("type", "original");
        payload.put("status", 0); // 0=草稿，1=发布
        payload.put("read_type", "public");

        // 元数据
        payload.put("reason", "");
        payload.put("original_link", "");
        payload.put("authorized_status", false);
        payload.put("check_original", false);

        // 系统信息
        payload.put("source", "pc_postedit");
        payload.put("not_auto_saved", 1);
        payload.put("creator_activity_id", "");

        // 封面设置
        payload.put("cover_images", new ArrayList<>());
        payload.put("cover_type", 1); // 1=无封面

        // 其他
        payload.put("vote_id", 0);
        payload.put("resource_id", "");
        payload.put("scheduled_time", 0); // 0=立即发布
        payload.put("is_new", 1);
        payload.put("sync_git_code", 0);

        return payload;
    }

    /**
     * 获取默认标签列表
     */
    private List<String> getDefaultTags() {
        return Arrays.asList("intellij-idea", "java", "编程");
    }

}
